"""
@Project : py.flask.excel
@File    : dateutil.py
@Author  : Liu Hongli
@Time    : 2024/5/24 15:40
"""
import pandas as pd
from datetime import datetime
from datetime import timedelta
from dateutil import rrule
from dateutil.rrule import SU, SA


def get_start_or_end_week(current_date):
    """获取当前日期所在周的开始和结束"""
    start_of_week = current_date - timedelta(days=current_date.weekday())
    end_of_week = start_of_week + timedelta(days=6)

    print(f"本周开始日期: {start_of_week}")
    print(f"本周结束日期: {end_of_week}")

    return end_of_week


def get_time_range_week():
    """获取时间范围的周"""

    # 定义开始和结束日期
    start_date = datetime(2024, 4, 28)
    end_date = datetime(2024, 5, 26)

    # start_date = get_start_or_end_week(start_date_)

    # 使用dateutil生成所有周的列表
    weeks = list(rrule.rrule(rrule.WEEKLY, wkst=SU, dtstart=start_date, until=end_date))
    # 生成当前日期开始，后续周日的日期
    # weeks = list(rrule(WEEKLY, byweekday=SU, dtstart=start_date, until=end_date))

    last_date = weeks and weeks[-1] or None

    if end_date != last_date:
        weeks.append(end_date)

    # 创建示例数据
    data = {'Date': pd.date_range(start='5/1/2024', periods=31, freq='D'),
            'Value': range(31)}

    df = pd.DataFrame(data)

    # 将日期转换为周
    df['Week'] = df['Date'].apply(compare_, args=(weeks,))

    # 按周分组并计算每周的总和
    weekly_sum = df.groupby('Week')['Value'].sum().reset_index()

    print(weekly_sum)


def compare_(date, weeks):
    try:
        return next(week for week in weeks if date <= week)
    except StopIteration:
        return None  # 或者您可以返回一个特定的值或者进行其他操作


if __name__ == '__main__':
    get_time_range_week()
    # get_start_or_end_week(datetime(2024,5,21))
